package org.koon;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import org.koon.web.Handler;
import org.koon.web.ParameterBinder;
import org.koon.web.Router;

import java.io.UnsupportedEncodingException;
import java.lang.reflect.InvocationTargetException;

public class Dispatcher {

    private Router router;

    public Dispatcher(Router router) {
        this.router = router;
    }

    public void dispatch(KooRequest httpRequest, MoonResponse httpResponse) {
        String path = httpRequest.getRequestLine().getPath();
        path = StrUtil.prependIfMissing(path,"/");
        Handler handler = router.directLookup(path);
        if (handler == null){
            httpResponse.setHttpStatus(HttpStatus.NOT_FOUND);
            return;
        }
        Object[] bind = ParameterBinder.bind(httpRequest, handler);
        try {
            Object o = handler.getMethod().invoke(handler.getObject(), bind);
            //httpResponse.setBody(JSONUtil.toJsonStr(o).getBytes());
            httpResponse.setBody(Koon.JSON_CONVERT.convertTo(o).getBytes(httpRequest.getCharset()));
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
    }
}
